<template>
  <div class="multi-step-form-container">
    <!-- 页面标题 -->
    <el-page-header @back="handleBack" content="新增课程项目"></el-page-header>

    <!-- 步骤条 - 自适应大小 -->
    <el-steps :active="activeStep" finish-status="success" class="steps-container">
      <el-step title="课程目录信息"></el-step>
      <el-step title="项目详情设置"></el-step>
      <el-step title="完成提交"></el-step>
    </el-steps>

    <!-- 主要内容区 -->
    <el-card class="form-card" shadow="always">
      <!-- 步骤1：课程目录信息 -->
      <div v-if="activeStep === 0" class="step-content">
        <el-form ref="courseForm" :model="courseForm" :rules="courseRules" label-width="120px">
          <!--  <el-form-item label="关联项目" prop="projectId">
            <el-input v-model="courseForm.projectId" placeholder="请输入关联projects表的外键" />
          </el-form-item> -->
          <!--  <el-form-item label="分类ID" prop="categoryId">
            <el-input v-model="courseForm.categoryId" placeholder="请输入分类ID" />
          </el-form-item> -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分类ID" prop="categoryId">
                <el-select v-model="courseForm.categoryId" placeholder="请选择分类" clearable filterable
                  :loading="categoryLoading">
                  <el-option v-for="item in categoryOptions" :key="item.id" :label="item.title" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课程标题" prop="title">
                <el-input v-model="courseForm.title" placeholder="请输入课程标题" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="图标" prop="iconClass">
            <image-upload v-model="courseForm.iconClass" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序序号 (1-100)" prop="sortOrder">
                <el-input v-model="courseForm.sortOrder" placeholder="请输入排序序号 (1-100)" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特点" prop="features">
                <el-input v-model="courseForm.features" placeholder="请输入特点，使用逗号分割" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="课程描述">
            <editor v-model="courseForm.description" :min-height="192" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：项目详情设置 -->
      <div v-if="activeStep === 1" class="step-content">
        <el-form ref="projectForm" :model="projectForm" :rules="projectRules" label-width="120px" class="project-form">
          <!-- 基础信息区域 -->
          <el-divider content-position="left">基础信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目标题" prop="title">
                <el-input v-model="projectForm.title" placeholder="请输入项目标题" maxlength="255"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="项目状态" prop="status">
                <el-select v-model="projectForm.status" placeholder="请选择项目状态">
                  <el-option label="未启用" value=0></el-option>
                  <el-option label="启用" value=1></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <!-- <el-col :span="12">
              <el-form-item label="项目标签" prop="tag">
                <el-input v-model="projectForm.tag" placeholder="请输入项目标签" maxlength="50"></el-input>
              </el-form-item>
            </el-col> -->

            <el-col :span="12">
              <el-form-item label="资源链接" prop="resourceUrl">
                <div class="resizable-input-container">
                  <el-input v-model="projectForm.resourceUrl" placeholder="请输入资源链接" maxlength="255" type="textarea"
                    :rows="3" class="resizable-input" ref="resourceInput"></el-input>
                  <div class="resize-handle" @mousedown="startResizing"></div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="分类图标URL" prop="img">
                <image-upload v-model="projectForm.img" />
              </el-form-item>
              <el-form-item label="内容区域标题" prop="contentTitle">
                <el-input v-model="projectForm.contentTitle" placeholder="请输入内容区域标题" maxlength="255"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 富文本编辑区域 -->
          <el-divider content-position="left">内容与介绍设置</el-divider>
          <el-form-item label="富文本内容">
            <editor v-model="projectForm.introDescription" :min-height="192" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤3：完成提交 -->
      <div v-if="activeStep === 2" class="step-content finish-step">
        <div class="finish-icon">
          <i class="el-icon-success"></i>
        </div>
        <h2>表单填写完成！</h2>
        <p>您已完成所有信息的填写，请确认无误后提交。</p>

        <div class="summary-card">
          <h3>课程目录信息摘要</h3>
          <p><strong>课程标题：</strong>{{ courseForm.title }}</p>
          <p><strong>分类ID：</strong>{{ courseForm.categoryId }}</p>

          <h3 style="margin-top: 15px;">项目详情摘要</h3>
          <p><strong>项目标题：</strong>{{ projectForm.title }}</p>
          <p><strong>项目状态：</strong>{{ projectForm.status === 1 ? '启用' : '未启用' }}</p>
        </div>
      </div>

      <!-- 步骤导航按钮 - 调整到右下角 -->
      <div class="step-navigation">
        <el-button v-if="activeStep > 0" @click="prevStep" class="prev-button">上一步</el-button>
        <div class="button-group-right">
          <el-button v-if="activeStep < 2" type="primary" @click="nextStep">下一步</el-button>
          <el-button v-if="activeStep === 2" type="primary" @click="submitAll">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { addItems } from "@/api/projectitems/items"
import { addProject } from '@/api/projectDetail/projectDetail'
import { getCates } from '@/api/cates/cate'
export default {
  name: 'MultiStepCourseForm',
  data() {
    return {
      categoryOptions: [],
      categoryLoading: false,
      // 当前激活的步骤，从0开始
      activeStep: 0,

      // 课程目录表单数据
      courseForm: {
        projectId: '',
        categoryId: '',
        title: '',
        description: '',
        iconClass: '',
        sortOrder:0,
        features: ''
      },

      // 课程目录表单验证规则
      courseRules: {
        projectId: [
          { required: true, message: '请输入关联projects表的外键', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请输入分类ID', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入课程标题', trigger: 'blur' },
          { max: 255, message: '课程标题不能超过255个字符', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序序号', trigger: 'blur' }
        ],
        features: [
          { max: 255, message: '特点不能超过255个字符', trigger: 'blur' }
        ]
      },

      // 项目详情表单数据
      projectForm: {
        title: '',
        status: null,
        resourceUrl: '',
        tag: '',
        img: '',
        contentTitle: '',
        introDescription: ''
      },

      // 项目详情表单验证规则
      projectRules: {
        title: [
          { required: true, message: '请输入项目标题', trigger: 'blur' },
          { max: 255, message: '项目标题不能超过255个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择项目状态', trigger: 'change' }
        ],
        tag: [
          { max: 50, message: '项目标签不能超过50个字符', trigger: 'blur' }
        ],
        resourceUrl: [
          { max: 255, message: '资源链接不能超过255个字符', trigger: 'blur' }
        ],
        img: [
          { max: 255, message: '图片URL不能超过255个字符', trigger: 'blur' }
        ]
      },

      // 用于记录资源链接输入框的resize状态
      resizing: false,
      startY: 0,
      startHeight: 0
    }
  },
  mounted() {
    this.fetchCategories()
  },
  methods: {
    fetchCategories() {
      getCates().then(res => {
        if (res.code === 200) {
          this.categoryOptions = res.data
          console.log(this.categoryOptions)
        } else {
          this.$message.error("获取分类列表失败", res.message)
        }
      })
    },
    // 下一步：验证当前步骤表单后进入下一步
    nextStep() {
      if (this.activeStep === 0) {
        // 验证课程目录表单
        this.$refs.courseForm.validate(valid => {
          if (valid) {
            this.activeStep++;
            // 滚动到页面顶部
            window.scrollTo(0, 0);
          }
        });
      } else if (this.activeStep === 1) {
        // 验证项目详情表单
        this.$refs.projectForm.validate(valid => {
          if (valid) {
            this.activeStep++;
            window.scrollTo(0, 0);
          }
        });
      }
    },

    // 上一步：直接返回上一步
    prevStep() {
      this.activeStep--;
      window.scrollTo(0, 0);
    },

    // 提交所有表单数据
    submitAll() {
      this.$confirm('确定要提交这些信息吗？', '确认提交', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 先添加项目
        const projectData = { ...this.projectForm };
        projectData.createBy = '当前登录用户';

        addProject(projectData).then(projectResponse => {
          const projectId = projectResponse.data.id;

          // 再添加课程目录，关联项目ID
          const courseData = { ...this.courseForm };
          courseData.projectId = projectId;

          addItems(courseData).then(() => {
            this.$message.success('提交成功！');
            this.$router.go(-1);
          }).catch(error => {
            this.$message.error('提交课程目录失败: ' + (error.message || '未知错误'));
          });
        }).catch(error => {
          this.$message.error('提交项目失败: ' + (error.message || '未知错误'));
        });
      }).catch(() => {
        this.$message.info('已取消提交');
      });
    },

    // 取消操作
    handleCancel() {
      this.$router.go(-1);
    },

    // 返回操作
    handleBack() {
      this.$router.go(-1);
    },

    // 开始调整资源链接输入框大小
    startResizing(e) {
      this.resizing = true;
      this.startY = e.clientY;
      this.startHeight = this.$refs.resourceInput.$el.clientHeight;

      document.addEventListener('mousemove', this.handleResizing);
      document.addEventListener('mouseup', this.stopResizing);
      e.preventDefault();
    },

    // 处理输入框大小调整
    handleResizing(e) {
      if (!this.resizing) return;

      const deltaY = e.clientY - this.startY;
      const newHeight = this.startHeight + deltaY;

      // 设置最小高度限制
      if (newHeight >= 40) {
        this.$refs.resourceInput.$el.style.height = `${newHeight}px`;
        const textarea = this.$refs.resourceInput.$el.querySelector('textarea');
        if (textarea) {
          textarea.style.height = `${newHeight}px`;
        }
      }
    },

    // 停止调整输入框大小
    stopResizing() {
      this.resizing = false;
      document.removeEventListener('mousemove', this.handleResizing);
      document.removeEventListener('mouseup', this.stopResizing);
    }
  },
  // 组件销毁时确保移除事件监听
  beforeDestroy() {
    if (this.resizing) {
      document.removeEventListener('mousemove', this.handleResizing);
      document.removeEventListener('mouseup', this.stopResizing);
    }
  }
}
</script>

<style scoped>
.multi-step-form-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

/* 步骤条自适应样式 */
.steps-container {
  margin: 20px 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.form-card {
  margin-top: 10px;
  position: relative;
}

.step-content {
  margin: 20px 0;
}

/* 步骤导航按钮样式 - 调整到右下角 */
.step-navigation {
  margin-top: 30px;
  padding: 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

/* 上一步按钮向左对齐 */
.prev-button {
  margin-right: auto;
}

/* 下一步和取消按钮向右对齐 */
.button-group-right {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 完成步骤样式 */
.finish-step {
  text-align: center;
  padding: 40px 0;
}

.finish-icon {
  font-size: 60px;
  color: #409eff;
  margin-bottom: 20px;
}

.summary-card {
  margin: 30px auto;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9f9f9;
  max-width: 600px;
  text-align: left;
}

/* 项目表单样式 */
.project-form {
  margin-top: 20px;
}

/* 可调整大小的输入框样式 */
.resizable-input-container {
  position: relative;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 6px;
  cursor: ns-resize;
  background-color: transparent;
}

.resize-handle:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

::v-deep .el-upload-list {
  margin-top: 10px;
}

::v-deep .el-divider--vertical {
  margin: 0 10px;
}

/* 响应式设计：适配不同屏幕尺寸 */
@media screen and (max-width: 768px) {
  .steps-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .step-navigation {
    flex-direction: column;
    align-items: flex-end;
    gap: 10px;
  }

  .prev-button {
    margin-right: 0;
    align-self: flex-start;
    width: 100%;
  }

  .button-group-right {
    width: 100%;
    justify-content: flex-end;
  }

  .el-col {
    width: 100% !important;
  }
}
</style>
